package com.kcsoft.welcome.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kcsoft.welcome.mapper.PrizeMapper;
import com.kcsoft.welcome.pojo.PageBean;
import com.kcsoft.welcome.pojo.Prize;
import com.kcsoft.welcome.service.PrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Service
public class PrizeServiceImpl implements PrizeService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Autowired
    PrizeMapper prizeMapper;

    @Override
    public void upload(MultipartFile file) {
        try {
            String uploadDir = uploadPath;

            Path upload = Paths.get(uploadDir);

            if(!Files.exists(upload)){
                Files.createDirectories(upload);
            }

            String originName = file.getOriginalFilename();
            String ext = originName.substring(originName.lastIndexOf("."));
            String fullname = UUID.randomUUID().toString() + ext;

            Path filePath = upload.resolve(fullname);

            file.transferTo(filePath);

            String path = filePath.toString();

            prizeMapper.add(path);


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageBean<Prize> list(Integer pageNum, Integer pageSize) {
        PageBean<Prize> pb = new PageBean<>();

        PageHelper.startPage(pageNum, pageSize);

        List<Prize> pl = prizeMapper.list();

        Page<Prize> page = (Page<Prize>) pl;

        pb.setTotal(page.getTotal());

        pb.setItems(page.getResult());

        return pb;
    }

    @Override
    public void update(Prize prize) {
        Prize pz = prizeMapper.get(prize.getId());

        if (prize.getUrl() != null) {
            pz.setUrl(prize.getUrl());
        }

        if (prize.getIntro() != null) {
            pz.setIntro(prize.getIntro());
        }

        prizeMapper.update(pz);
    }

    @Override
    public void delete(Integer id) {
        Prize pz = prizeMapper.get(id);

        File file = new File(pz.getUrl());

        if (file.exists() && file.isFile()) {
            file.delete();
        }
        prizeMapper.delete(id);
    }
}
